import axios from 'axios'
import { Toast, Dialog } from 'vant'
// 根据环境不同引入不同api地址
import { baseApi } from '@/config'
import router from '@/router'
import { Tips } from '@/utils/index'
// create an axios instance
const service = axios.create({
  baseURL: baseApi,
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // 等待时间
})

// request拦截器 request interceptor
service.interceptors.request.use(
  config => {
    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      Tips.loading(config.message)
    }
    if (localStorage.getItem('token')) {
      config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token')
    }
    config.baseURL = config.baseURL + '/' + (config.version ? config.version : 'v2')
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug

    return Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  response => {
    Toast.clear()
    const res = response.data
    if (res.status && res.status !== 200) {
      Tips.error(res.msg)
      return Promise.reject(res || 'error')
    } else {
      if (res.code !== 0) {
        return Promise.resolve(res.data)
      } else {
        Tips.error(res.msg)
        return Promise.reject(res || 'error')
      }
    }
  },
  error => {
    Toast.clear()
    if (error.response.status === 401) {
      Dialog({ message: '登录过期，请重新登录' }).then(() => {
        localStorage.removeItem('token')
        router.replace('/login')
      })
    } else {
      Tips.error(error.response.data.message)
    }
    return Promise.reject(error)
  }
)
export default service
